import React, { useState, useEffect, useRef } from "react";
import "./adventure.css";
import "./reward.css";
import type { GameStat } from "../../types";

interface AdventureProps {
  characterName: string;
  stats: GameStat[];
  onClose: () => void;
}

interface Choice {
  id: number;
  text: string;
}

// 奖励物品
interface GameItem {
  id: number;
  name: string;
  type: string;
  desc?: string;
  effect?: string;
}

// 奖励数据
interface GameReward {
  cultivation?: number;
  spirit_stone?: number;
  items?: GameItem[];
}

// 下一分支
interface GameBranch {
  has_next: boolean;
  next_story?: string;
  choices?: Choice[];
}

// 游戏数据事件
interface GameDataEvent {
  story?: string;
  result?: string;
  reward?: GameReward;
  next_branch?: GameBranch;
  choices?: Choice[];
  conversation_id?: string;
}

interface UserContext {
  user_id: number;
  realm: string;
  realm_level: string;
  sect: string; // 新增：宗门
  talent: number;
  comprehension: number;
  luck: number;
  adventure_count: number;
  equipments: any[];
  items: any[];
}

const Adventure: React.FC<AdventureProps> = ({
  characterName,
  stats,
  onClose,
}) => {
  // 状态管理
  const [displayedText, setDisplayedText] = useState<string>("");
  const [choices, setChoices] = useState<Choice[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [conversationId, setConversationId] = useState<string>("");
  const [history, setHistory] = useState<any[]>([]);
  const [reward, setReward] = useState<GameReward | null>(null);
  const [showRewardPopup, setShowRewardPopup] = useState<boolean>(false);

  // 用于打字机效果的引用
  const fullTextRef = useRef<string>(""); // 完整的待显示文本（实时累加）
  const displayIndexRef = useRef<number>(0); // 当前已显示的字符索引
  const typingIntervalRef = useRef<number | null>(null);
  const abortControllerRef = useRef<AbortController | null>(null);

  // 组件挂载时启动打字机和首次历练
  useEffect(() => {
    // 启动打字机循环
    startTypingLoop();

    // 开始首次历练
    startAdventure();

    // 组件卸载时清理
    return () => {
      if (typingIntervalRef.current) {
        clearInterval(typingIntervalRef.current);
      }
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  // 🎬 打字机循环（持续运行，实时显示）
  const startTypingLoop = () => {
    if (typingIntervalRef.current) {
      clearInterval(typingIntervalRef.current);
    }

    typingIntervalRef.current = setInterval(() => {
      // 如果已显示索引 < 完整文本长度，继续打字
      if (displayIndexRef.current < fullTextRef.current.length) {
        displayIndexRef.current++;
        const newDisplayText = fullTextRef.current.substring(
          0,
          displayIndexRef.current
        );
        setDisplayedText(newDisplayText);
      }
    }, 50); // 50ms/字符（每秒20字）
  };

  // 构造用户上下文
  const buildUserContext = (): UserContext => {
    // 从stats中提取数据
    const realmStat = stats.find((s) => s.label === "境界");
    const comprehensionStat = stats.find((s) => s.label === "悟性");
    const sectStat = stats.find((s) => s.label === "宗门");

    return {
      user_id: 1, // TODO: 从认证信息获取真实user_id
      realm: realmStat?.value.replace(/\d+层$/, "") || "练气期",
      realm_level: realmStat?.value.match(/\d+/)?.[0] || "1",
      sect: sectStat?.value || "散修", // 默认散修
      talent: 70, // TODO: 从用户数据获取
      comprehension: parseInt(comprehensionStat?.value || "10"),
      luck: 70, // TODO: 从用户数据获取
      adventure_count: history.length + 1,
      equipments: [], // TODO: 从背包获取装备数据
      items: [], // TODO: 从背包获取物品数据
    };
  };

  // 开始历练（首次或重新开始）
  const startAdventure = async () => {
    setIsLoading(true);

    // 重置文本和索引
    fullTextRef.current = "";
    displayIndexRef.current = 0;
    setDisplayedText("");
    setChoices([]);

    try {
      // 创建新的 AbortController
      abortControllerRef.current = new AbortController();

      const userContext = buildUserContext();
      const userContextJson = JSON.stringify(userContext);

      const requestBody = {
        user_id: "1",
        additional_messages: [
          {
            role: "user",
            type: "question",
            content: userContextJson,
            content_type: "text",
          },
        ],
        parameters: {},
      };

      // 发送SSE请求
      const response = await fetch(
        "http://localhost:8080/api/v1/game/adventure/stream",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(requestBody),
          signal: abortControllerRef.current.signal,
        }
      );

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // 处理流式响应
      await processStreamResponse(response);
    } catch (error: any) {
      if (error.name === "AbortError") {
        console.log("请求已取消");
      } else {
        console.error("历练请求失败:", error);
        fullTextRef.current = "历练遇到了问题，请稍后再试...";
        displayIndexRef.current = 0;
      }
    } finally {
      setIsLoading(false);
    }
  };

  // 处理流式响应
  const processStreamResponse = async (response: Response) => {
    const reader = response.body?.getReader();
    const decoder = new TextDecoder();

    if (!reader) {
      throw new Error("无法读取响应流");
    }

    let buffer = "";
    let tempConversationId = "";
    let followUpSuggestions: string[] = [];

    while (true) {
      const { done, value } = await reader.read();

      if (done) {
        break;
      }

      // 解码数据块
      buffer += decoder.decode(value, { stream: true });

      // 按行分割
      const lines = buffer.split("\n");
      buffer = lines.pop() || ""; // 保留最后不完整的行

      let currentEventType = "";

      for (const line of lines) {
        const trimmedLine = line.trim();

        if (trimmedLine === "" || trimmedLine === "event:done") {
          continue;
        }

        // 解析事件类型
        if (trimmedLine.startsWith("event:")) {
          currentEventType = trimmedLine.substring(6);
          console.log("事件类型:", currentEventType);
          continue;
        }

        // 解析数据
        if (trimmedLine.startsWith("data:")) {
          const jsonData = trimmedLine.substring(5).trim();

          if (jsonData === "[DONE]") {
            break;
          }

          try {
            const data = JSON.parse(jsonData);

            // 🎮 处理游戏数据事件（后端推送的完整数据）
            if (currentEventType === "game.data") {
              const gameData = data as GameDataEvent;
              console.log("🎮 接收到游戏数据:", gameData);

              // 1️⃣ 拼接完整的故事文本
              let fullStory = "";

              if (gameData.story) {
                // 首次历练：只有 story
                fullStory = gameData.story;
                console.log("  📜 首次历练故事");
              } else if (gameData.result) {
                // 选择后：result + next_story
                fullStory = gameData.result;
                console.log("  📜 战斗/事件结果");

                if (gameData.next_branch?.next_story) {
                  fullStory += "\n\n" + gameData.next_branch.next_story;
                  console.log("  📜 追加下一段故事");
                }
              }

              console.log("📖 完整故事文本 (长度:", fullStory.length, ")");
              console.log("  预览:", fullStory.substring(0, 100));

              // 2️⃣ 设置到打字机队列（覆盖之前的内容）
              fullTextRef.current = fullStory;
              displayIndexRef.current = 0; // 重置索引，触发打字机

              // 3️⃣ 提取奖励
              if (gameData.reward) {
                const hasReward =
                  gameData.reward.cultivation ||
                  gameData.reward.spirit_stone ||
                  (gameData.reward.items && gameData.reward.items.length > 0);

                if (hasReward) {
                  console.log("🎁 获得奖励:", gameData.reward);
                  setReward(gameData.reward);
                  setShowRewardPopup(true);

                  // 3秒后自动隐藏奖励弹窗
                  setTimeout(() => setShowRewardPopup(false), 3000);
                }
              }

              // 4️⃣ 提取选项
              const choices =
                gameData.next_branch?.choices || gameData.choices || [];
              if (choices.length > 0) {
                followUpSuggestions = choices.map((choice: any) => choice.text);
                console.log("✅ 提取到选项:", followUpSuggestions);
              }

              // 5️⃣ 提取 conversation_id
              if (gameData.conversation_id) {
                tempConversationId = gameData.conversation_id;
                setConversationId(gameData.conversation_id);
                console.log("🔗 会话ID:", gameData.conversation_id);
              }

              continue;
            }

            // 💬 处理 delta 消息（逐字推送，用于打字机效果）✅ 流式提取 story
            if (currentEventType === "conversation.message.delta") {
              if (data.content) {
                console.log(
                  "💬 接收 delta:",
                  data.content.substring(0, 50),
                  data.content.length > 50 ? "..." : ""
                );
                // 不再累加到 fullTextRef，等待 game.data 事件
              }
              continue;
            }

            // 🔗 提取 conversation_id
            if (data.conversation_id && !tempConversationId) {
              tempConversationId = data.conversation_id;
              setConversationId(data.conversation_id);
              console.log("🔗 获取到 conversation_id:", data.conversation_id);
            }

            // ⚠️ 旧版兼容：处理 data.message 格式（如果 AI 返回这种格式）
            if (data.message) {
              const message = data.message;

              console.log("接收到消息:", {
                type: message.type,
                content: message.content?.substring(0, 50), // 只显示前50字符
                contentLength: message.content?.length,
              });

              // 累加答案内容（type === 'answer'）- 用于打字机效果
              if (message.type === "answer" && message.content) {
                console.log("✅ 累加答案内容:", message.content);
                fullTextRef.current += message.content;
              }

              // 忽略 follow_up 建议，使用 game.data 中的 choices
            }
          } catch (e) {
            console.error("JSON解析失败:", e, jsonData);
          }
        }
      }
    }

    // 流结束后的统计
    console.log("📊 流结束统计:", {
      fullTextLength: fullTextRef.current.length,
      textPreview: fullTextRef.current.substring(0, 200),
      choicesCount: followUpSuggestions.length,
      conversationId: tempConversationId,
    });

    if (followUpSuggestions.length > 0) {
      const choiceList: Choice[] = followUpSuggestions.map((text, index) => ({
        id: index + 1,
        text: text,
      }));
      setChoices(choiceList);
    } else {
      // 如果没有 follow_up，提供默认选项
      setChoices([
        { id: 1, text: "继续探索" },
        { id: 2, text: "返回" },
      ]);
    }
  };

  // 处理用户选择
  const handleChoice = async (choiceId: number) => {
    const selectedChoice = choices.find((c) => c.id === choiceId);
    if (!selectedChoice) return;

    // 保存历史记录（使用当前完整文本）
    setHistory((prev) => [
      ...prev,
      {
        story: fullTextRef.current,
        choice: selectedChoice.text,
      },
    ]);

    setIsLoading(true);

    // 重置文本和索引
    fullTextRef.current = "";
    displayIndexRef.current = 0;
    setDisplayedText("");
    setChoices([]);

    try {
      // 创建新的 AbortController
      abortControllerRef.current = new AbortController();

      const userContext = buildUserContext();

      const userChoiceContext = {
        user_choice: choiceId,
        user_context: userContext,
        history: history,
      };

      const userChoiceJson = JSON.stringify(userChoiceContext);

      const requestBody = {
        user_id: "1",
        conversation_id: conversationId,
        additional_messages: [
          {
            role: "user",
            type: "question",
            content: userChoiceJson,
            content_type: "text",
          },
        ],
        parameters: {},
      };

      // 发送SSE请求
      const response = await fetch(
        "http://localhost:8080/api/v1/game/adventure/stream",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(requestBody),
          signal: abortControllerRef.current.signal,
        }
      );

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // 处理流式响应
      await processStreamResponse(response);
    } catch (error: any) {
      if (error.name === "AbortError") {
        console.log("请求已取消");
      } else {
        console.error("选择处理失败:", error);
        fullTextRef.current = "处理选择时遇到问题，请重试...";
        displayIndexRef.current = 0;
      }
    } finally {
      setIsLoading(false);
    }
  };

  // 跳过打字机动画
  const skipTyping = () => {
    // 直接将显示索引跳到最大值
    displayIndexRef.current = fullTextRef.current.length;
    setDisplayedText(fullTextRef.current);
  };

  return (
    <div className="adventure-container">
      <div className="adventure-header">
        <h2>🗡️ 历练奇遇</h2>
        <button className="close-button" onClick={onClose}>
          ✕
        </button>
      </div>

      <div className="adventure-content">
        {/* 奖励弹窗 */}
        {showRewardPopup && reward && (
          <div className="reward-popup">
            <h3>🎉 获得奖励</h3>
            <div className="reward-list">
              {reward.cultivation && (
                <div className="reward-item cultivation">
                  <span className="icon">📈</span>
                  <span className="text">修为 +{reward.cultivation}</span>
                </div>
              )}
              {reward.spirit_stone && (
                <div className="reward-item spirit-stone">
                  <span className="icon">💎</span>
                  <span className="text">灵石 +{reward.spirit_stone}</span>
                </div>
              )}
              {reward.items?.map((item, index) => (
                <div key={index} className="reward-item item">
                  <span className="icon">🎁</span>
                  <span className="text">{item.name}</span>
                  {item.desc && <span className="desc">({item.type})</span>}
                </div>
              ))}
            </div>
          </div>
        )}
        {/* 故事展示区 */}
        <div className="story-display">
          <div className="story-text">
            {displayedText || "准备开始你的历练之旅..."}
            {displayIndexRef.current < fullTextRef.current.length && (
              <span className="typing-cursor">▌</span>
            )}
          </div>

          {displayIndexRef.current < fullTextRef.current.length && (
            <button className="skip-button" onClick={skipTyping}>
              跳过动画 ⏭️
            </button>
          )}
        </div>

        {/* 选项按钮区 */}
        <div className="choices-container">
          {isLoading && (
            <div className="loading-indicator">
              <div className="spinner"></div>
              <p>正在生成历练内容...</p>
            </div>
          )}

          {!isLoading &&
            choices.length > 0 &&
            displayIndexRef.current >= fullTextRef.current.length && (
              <>
                <h3>请选择你的行动：</h3>
                <div className="choices-grid">
                  {choices.map((choice) => (
                    <button
                      key={choice.id}
                      className="choice-button"
                      onClick={() => handleChoice(choice.id)}
                    >
                      {choice.text}
                    </button>
                  ))}
                </div>
              </>
            )}
        </div>

        {/* 用户状态提示 */}
        <div className="adventure-status">
          <span>🧙 {characterName}</span>
          <span>🌟 对话轮次: {history.length + 1}</span>
          {conversationId && (
            <span>🔗 会话ID: {conversationId.substring(0, 8)}...</span>
          )}
        </div>
      </div>
    </div>
  );
};

export default Adventure;
